package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.footview.CustomerFooter;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.model.ProvinceModel;
import com.cheer.ba.presenter.impl.FindOilPresenter;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.adapter.FindOilAdp;
import com.cheer.ba.view.adapter.OilCardAdp;
import com.cheer.ba.view.animation.CustomAnimation;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.view.dialog.DialogUtils;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.cheer.ba.widget.observable.ObservableListView;
import com.cheer.ba.widget.observable.ObservableRecyclerView;
import com.cheer.pickerview.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 加油卡列表界面
 *
 * @author HQ
 *         created at 2017/5/10 0010 16:58
 */
public class OilCardAty extends BaseCommAty implements AdapterView.OnItemClickListener, View.OnClickListener {

    @BindView(R.id.id_oil_card_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_card_listv)
    ObservableListView mObserListv;
    private CommonAdapter<OilCardInfoModel> mAdapter;
    List<OilCardInfoModel> mOilCards = new ArrayList<OilCardInfoModel>();

    //确定按钮
    @BindView(R.id.id_oil_sure_btn)
    Button mBtnSure;

    //弹出框
    private PopupWindow mPopWindow;

    private ImageView mRightAddView;

    //记录点击列表是否返回 true 返回
    private boolean isBack;

    //省份名称
    private String mSaveProvName;
    //存储省份名称
    private ArrayList<String> mProvinces = new ArrayList<String>();

    //记录点击的model
    private OilCardInfoModel mSaveCheckModel;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_oil_card_list, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return !mOilCards.isEmpty();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.mine_oil_cards));
        findViewById(R.id.id_oil_sure_btn).setOnClickListener(this);
        isBack = getIntent().getBooleanExtra(IntentKey.General.KEY_PAGE, false);
        if (isBack) {
            mBtnSure.setVisibility(View.VISIBLE);
        } else {
            mBtnSure.setVisibility(View.GONE);
        }

        final View mView = getLayoutInflater().inflate(R.layout.popup_choose_card, null);
        mView.findViewById(R.id.id_search_key_txt).setOnClickListener(this);
        mView.findViewById(R.id.id_add_oil_card_txt).setOnClickListener(this);
        mPopWindow = DialogUtils.initDropPopup(mView);

        mRightAddView = setTitleIcon(R.drawable.ic_show_pop, false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == mPopWindow) {
                    mPopWindow = DialogUtils.initDropPopup(mView);
                    mPopWindow.showAsDropDown(mRightAddView);
                } else {
                    if (mPopWindow.isShowing()) {
                        mPopWindow.dismiss();
                    } else {
                        mPopWindow.showAsDropDown(mRightAddView);
                    }
                }
            }
        });

        initSearchBar(mObserListv, new SearchBarClick() {
            @Override
            public void onSearchBarClick() {
                Intent intent = new Intent(aty, SearchAty.class);
                intent.putExtra(IntentKey.General.KEY_PAGE, isBack);
                showActivity(aty, intent);
            }
        }, "搜索");

        setXRefreshView(mXRefreshView, true, false, false, false, new CheerHeadView(aty), null);
        mAdapter = new CommonAdapter<OilCardInfoModel>(aty, mOilCards, R.layout.adp_my_oilcard) {
            @Override
            public void convert(final ViewHolder helper, final OilCardInfoModel item) {
                if (null == item) {
                    return;
                }
                final CheckBox mCheckBox = (CheckBox) helper.getView(R.id.id_check_box);
                if (isBack) {
                    mCheckBox.setVisibility(View.VISIBLE);
                    if (checkMap.get(helper.getPosition(), false)) {
                        mCheckBox.setChecked(true);
                    } else {
                        mCheckBox.setChecked(false);
                    }
                    mCheckBox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mCheckBox.isChecked()) {
                                mSaveCheckModel = item;
                                mAdapter.setCheckAtPosFalse(helper.getPosition(), true);
                            } else {
                                mSaveCheckModel = null;
                                mAdapter.setCheckAtPosFalse(helper.getPosition(), false);
                            }
                        }
                    });
                } else {
                    mCheckBox.setVisibility(View.GONE);
                }
                helper.setText(R.id.id_oil_card_num_txt, StringUtils.replaceBankString(item.getCardNum(), 0));
                helper.setText(R.id.id_oil_card_txt, "加油啦车队卡");
                if (item.getCardType() == 1) {
                    helper.setText(R.id.id_oil_name_txt, "中国石油（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_china_oil_logo);
                } else if (item.getCardType() == 2) {
                    helper.setText(R.id.id_oil_name_txt, "中国石化（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_shihua_logo);
                } else {
                    helper.setText(R.id.id_oil_name_txt, "中国海油（" + item.getProvince() + "）");
                    helper.setImageResource(R.id.id_oil_logo_img, R.drawable.ic_haiyou_logo);
                }
                TextView mTxtCardActivity = (TextView) helper.getView(R.id.id_activity_txt);
                if (item.getCardStatus() == 1) {
                    //未激活
                    mTxtCardActivity.setText("未激活");
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.red));
                } else {
                    mTxtCardActivity.setText("余额：" + Currency.returnDollar(item.getBalance()));
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.white));
                }
            }
        };
        mObserListv.setAdapter(mAdapter);
        mObserListv.setOnItemClickListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        //获得省级数据
        final ArrayList<ProvinceModel> provinces = (ArrayList<ProvinceModel>) ((OilMealPresenter) presenter).getData(4, false);
        if (null != provinces && !provinces.isEmpty()) {
            mProvinces.clear();
            for (ProvinceModel p : provinces) {
                mProvinces.add(p.mProvinceName);
            }
        }

        loadData(true);
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false);
            }
        });
    }

    /**
     * 加载数据
     */
    public void loadData(boolean isShLowoad) {
        ((OilMealPresenter) presenter).getMyOilCards(isShLowoad, "0", mSaveProvName, "", "", "", "");
        if (!isShLowoad) {
            stopRefresh(mXRefreshView, 2000);
        }
    }

    /**
     * 选择省份
     */
    public void chooseProvs() {
        Util.alertBottomWheelOption(aty, mProvinces, new Util.OnWheelViewClick() {
            @Override
            public void onClick(View view, int postion) {
                mOilCards.clear();
                mSaveProvName = mProvinces.get(postion);
                loadData(true);
            }
        }, 16);
    }

    @Override
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_search_key_txt:
                mPopWindow.dismiss();
                //城市筛选
                chooseProvs();
                break;
            case R.id.id_add_oil_card_txt:
                mPopWindow.dismiss();
                //添加油卡
                showActivity(aty, AddOilCardAty.class);
                break;
            //确定按钮
            case R.id.id_oil_sure_btn:
                if (null == mSaveCheckModel) {
                    SVProgressHUD.showInfoWithStatus(aty, "请选择油卡");
                } else {
                    BaseEvent event = new BaseEvent();
                    event.type = IntentKey.Oil.KEY_OIL_MODEL;
                    event.model = mSaveCheckModel;
                    EventBus.getDefault().post(event);
                    finish();
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        mXRefreshView.stopRefresh();
        if (null != t) {
            if (TextUtils.equals(ConstantTag.MY_OIL_CARDS, tag)) {
                //获得油卡列表成功
                List<OilCardInfoModel> oilCards = (List<OilCardInfoModel>) t;

                mOilCards.clear();
                mOilCards.addAll(oilCards);
                mAdapter.notifyDataSetChanged();
            } else if (TextUtils.equals(ConstantTag.SET_DEFAULT_CARD, tag)) {
                SVProgressHUD.showInfoWithStatus(aty, "设置默认卡成功");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //设置默认卡成功
                        ((OilMealPresenter) presenter).getMyOilCards(true, "0", mSaveProvName, "", "", "", "");
                    }
                }, 2000);
            } else if (TextUtils.equals(ConstantTag.DATA_SUCCESS_NULL, tag)) {
                //没有油卡了
                mOilCards.clear();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        OilCardInfoModel model = (OilCardInfoModel) mAdapter.getItem(position - 1);
        Intent intent = new Intent(aty, OilCardDetailAty.class);
        intent.putExtra(IntentKey.General.KEY_MODEL, model);
        showActivity(aty, intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.Oil.KEY_OIL_MODEL)) {
            //添加油卡成功,搜索界面选择油卡成功
            boolean flag = event.flag;
            if (flag) {
                finish();
            } else {
                mSaveProvName = "";
                mOilCards.clear();
                loadData(true);
            }
        } else if (TextUtils.equals(type, IntentKey.Oil.DEL_OIL_CARD)) {
            //移除油卡
            loadData(false);
        } else if (TextUtils.equals(type, IntentKey.Oil.OIL_ACTIVITY_SUCCESS)) {
            //激活油卡成功
            loadData(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentCode.General.JUMP_SEARCH) {
            if (resultCode == IntentCode.General.BACK_SEARCH) {
                OilCardInfoModel model = (OilCardInfoModel) data.getSerializableExtra(IntentKey.General.KEY_MODEL);
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Oil.KEY_OIL_MODEL;
                event.model = model;
                EventBus.getDefault().post(event);
                finish();
            }
        }
    }
}
